package chpt02;

public class SquareRootTest {
	public static void main(String[] args) {
		testCalculateSquareRoot();
	}

	public static void testCalculateSquareRoot() {
		double[] testNumbers = { 0.0, -1, 1.0, 2.0, 25.0, 9999999.0, 0.25, 0.81 };
		for (double number : testNumbers) {
			double result = sqrt(number);
			System.out.println("对" + number + "求开根号：" + result);
		}
	}

	public static double sqrt(double number) {
		if (number < 0) {
			return Double.NaN;
		}
		if (number == 0) {
			return 0;
		}
		double epsilon = 1e-6; // 误差范围
		double low = 0; // 猜测的下限
		double high = Math.max(1, number); // 猜测下限
		double guess = (low + high) / 2.0; // 初始猜测值
		int n = 0;
		while (Math.abs(guess * guess - number) > epsilon) {
			n++;
			if (guess * guess < number) {
				low = guess;
			} else {
				high = guess;
			}
			guess = (low + high) / 2.0; // 更新猜测值
		}
		System.out.print("迭代了" + n + "轮!");
		return guess;
	}
}